extends Panel

signal item_clicked(item: Item)

@onready var icon = $Icon
@onready var amount_label = $Amount
var slot: InventorySlot
var default_style: StyleBoxFlat
var hover_style: StyleBoxFlat
var context_menu: PopupMenu

# 拖拽相关变量
var dragging = false
var drag_preview: TextureRect = null
var original_pos: Vector2

func _ready():
	default_style = get_theme_stylebox("panel").duplicate()
	hover_style = default_style.duplicate()
	hover_style.bg_color = Color(0.2, 0.2, 0.2, 1)
	hover_style.border_color = Color(0.4, 0.4, 0.4, 1)
	
	mouse_entered.connect(_on_mouse_entered)
	mouse_exited.connect(_on_mouse_exited)
	gui_input.connect(_on_gui_input)
	_setup_context_menu()

func _on_mouse_entered():
	add_theme_stylebox_override("panel", hover_style)

func _on_mouse_exited():
	add_theme_stylebox_override("panel", default_style)

func set_slot(new_slot: InventorySlot):
	slot = new_slot
	if slot:
		update_slot(slot)

func update_slot(inventory_slot: InventorySlot):
	if inventory_slot and inventory_slot.item:
		icon.texture = inventory_slot.item.icon
		amount_label.text = str(inventory_slot.amount) if inventory_slot.amount > 1 else ""
		icon.show()
	else:
		icon.hide()
		amount_label.text = ""

func _get_type_text(type: Item.ItemType) -> String:
	match type:
		Item.ItemType.CONSUMABLE:
			return "消耗品"
		Item.ItemType.EQUIPMENT:
			return "装备"
		Item.ItemType.MATERIAL:
			return "材料"
		Item.ItemType.QUEST:
			return "任务物品"
		Item.ItemType.KEY:
			return "关键物品"
		_:
			return "未知" 

func _on_gui_input(event: InputEvent):
	if event is InputEventMouseButton:
		if event.pressed:
			if event.button_index == MOUSE_BUTTON_LEFT:
				if slot and slot.item:
					if event.double_click:
						# 双击处理...
						pass
					else:
						item_clicked.emit(slot.item)  # 单击时发送信号
			elif event.button_index == MOUSE_BUTTON_RIGHT:
				if slot and slot.item:
					context_menu.popup(Rect2(get_global_mouse_position(), Vector2(100, 0)))

func _setup_context_menu():
	context_menu = PopupMenu.new()
	add_child(context_menu)
	
	# 添加菜单项
	context_menu.add_item("使用/装备", 0)
	context_menu.add_item("丢弃", 1)
	
	# 连接信号
	context_menu.id_pressed.connect(_on_context_menu_selected)

func _on_context_menu_selected(id: int):
	if not slot or not slot.item:
		return
		
	match id:
		0: # 使用/装备
			if slot.item.type == Item.ItemType.EQUIPMENT:
				print("装备物品：", slot.item.name)
				print("物品ID：", slot.item.id, " 图标路径：", slot.item.icon.resource_path)
				var player = get_tree().get_first_node_in_group("player")
				if player and slot.item.icon:
					# 特殊处理"裁星者"武器
					if slot.item.name == "裁星者":
						print("装备特殊武器：裁星者")
						# 播放特殊音效
						var audio_player = AudioStreamPlayer.new()
						# 使用通用音效，不预加载不存在的资源
						var audio_stream = AudioStreamPolyphonic.new()
						audio_player.stream = audio_stream
						audio_player.volume_db = -10
						audio_player.finished.connect(func(): audio_player.queue_free())
						get_tree().root.add_child(audio_player)
						audio_player.play()
						
						# 使用新创建的特效场景
						var effect_scene = load("res://scenes/effects/equip_effect.tscn")
						if effect_scene:
							var effect = effect_scene.instantiate()
							player.add_child(effect)
							effect.position = Vector2(0, -20)  # 在玩家上方
					
					print("调用玩家特效方法，是否为武器：true")
					# 传递物品名称作为额外参数
					if player.has_method("show_item_effect_with_name"):
						# 确保延迟一帧调用，避免在同一帧内创建和销毁节点
						await get_tree().process_frame
						player.show_item_effect_with_name(slot.item.icon, slot.item.name)
					else:
						player.show_item_effect(slot.item.icon, true)
			else:
				print("使用物品：", slot.item.name)
				var player = get_tree().get_first_node_in_group("player")
				if player and slot.item.icon:
					print("调用玩家特效方法，是否为武器：false")
					player.show_item_effect(slot.item.icon, false)
		1: # 丢弃
			print("丢弃物品：", slot.item.name)
			var inventory = get_node("/root/InventoryManager").inventory
			inventory.remove_item(slot.item, 1)

func _process(_delta):
	if dragging and drag_preview:
		# 使用相对于 UI 的位置
		var mouse_pos = get_viewport().get_mouse_position()
		drag_preview.position = mouse_pos - drag_preview.custom_minimum_size / 2

func _start_drag():
	if not slot.item:
		return
		
	dragging = true
	icon.modulate.a = 0.3  # 降低原始图标的透明度
	
	# 创建拖拽预览
	drag_preview = TextureRect.new()
	drag_preview.texture = slot.item.icon
	drag_preview.custom_minimum_size = icon.size  # 使用原始图标的尺寸
	drag_preview.size = icon.size                 # 设置大小和原始图标一致
	drag_preview.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
	drag_preview.modulate.a = 0.7
	drag_preview.z_index = 100
	drag_preview.mouse_filter = Control.MOUSE_FILTER_IGNORE
	
	# 添加到 UI 层级
	var inventory_ui = get_tree().get_nodes_in_group("inventory_ui")[0]
	inventory_ui.add_child(drag_preview)
	
	# 设置初始位置
	var mouse_pos = get_viewport().get_mouse_position()
	drag_preview.position = mouse_pos - drag_preview.size / 2  # 使用 size 而不是 custom_minimum_size

func _end_drag():
	if not dragging:
		return
		
	dragging = false
	icon.modulate.a = 1.0  # 恢复原始图标的透明度
	
	if drag_preview:
		drag_preview.queue_free()
		drag_preview = null
	
	# 检查是否在其他槽位上
	var target_slot = _get_slot_at_position(get_global_mouse_position())
	if target_slot and target_slot != self:
		_swap_items(target_slot)

func _get_slot_at_position(pos: Vector2) -> Node:
	# 获取鼠标位置下的所有控件
	var nodes = get_tree().get_nodes_in_group("inventory_slot")
	for node in nodes:
		if node.get_global_rect().has_point(pos):
			return node
	return null

func _swap_items(target_slot):
	var inventory = get_node("/root/InventoryManager").inventory
	var from_index = get_index()
	var to_index = target_slot.get_index()
	
	# 交换物品
	var temp_item = inventory.slots[from_index].item
	var temp_amount = inventory.slots[from_index].amount
	
	inventory.slots[from_index].item = inventory.slots[to_index].item
	inventory.slots[from_index].amount = inventory.slots[to_index].amount
	
	inventory.slots[to_index].item = temp_item
	inventory.slots[to_index].amount = temp_amount
	
	inventory.inventory_changed.emit()

func _enter_tree():
	add_to_group("inventory_slot")

func _exit_tree():
	remove_from_group("inventory_slot") 
